<?php

namespace App\Http\Controllers;

use App\Sentence;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SentencesController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function latest(Request $request, Sentence $sentence)
    {
        return $sentence->show($request);
    }

    public function search(Request $request, Sentence $sentence)
    {
        return $sentence->where('content', 'like', '%'.$request->keyword.'%')->show($request)->appends(['keyword']);
    }

    public function show(Sentence $sentence, $id)
    {
        return $sentence->with(['user'])->findOrFail($id);
    }

    public function post(Request $request, Sentence $sentence)
    {
        $this->validate($request, [
            'title' => 'max:255',
            'content' => 'required',
            'source' => 'max:255',
            'is_original' => 'integer|between:0,255',
        ]);

        $sentence->fill($request->only(['title', 'content', 'is_original', 'source']));
        $sentence->user_id = Auth::id();
        $sentence->save();

        return ['message' => '分享成功'];
    }
}
